<template>
    <div class="commm-player-main">
      <div id="container" ref="container" :style="customStyle" @dblclick=""/>
      <div v-show="loaded" class="buttons-div" ref="buttonsBox">
        <div>
          <i v-if="playing" class="iconfont icon-stop player-btn" title="停止" @click="stop"></i>
          <i v-if="!playing" class="iconfont icon-play player-btn" title="播放" @click="playBtnClick"></i>
          <i v-if="playing" class="iconfont icon-pause player-btn" title="暂停" @click="pause"></i>

          <i v-if="isNotMute" class="iconfont icon-audio-high jessibuca-btn" title="关闭声音" @click="soundOff(0)"></i>
          <i v-if="!isNotMute" class="iconfont icon-audio-mute jessibuca-btn" title="开启声音" @click="soundOff(1)"></i>
        </div>
        <div >
          <Slider title="音量" v-model="currentVolume" :max="volume.max" :min="volume.min" style="width:60px;margin-right: 5px" :disabled = "!isNotMute"></Slider>
        </div>

        <div>
          <div class="performance-span0" v-if="performance.currValue==0">卡顿</div>
          <div class="performance-span1" v-if="performance.currValue==1">流畅</div>
          <div class="performance-span2" v-if="performance.currValue==2">非常流畅</div>

        </div>
        <div style="margin-left: 10px" v-show="1==0">
          <Slider title="缓存时间(秒)" v-model="currentBuffer" :max="buffer.max" :min="buffer.min" style="width:60px;margin-right: 5px" ></Slider>
        </div>
        <div class="buttons-div-right">
          <span class="player-btn">{{kBps}} kb/s</span>
          <i v-if="!fullscreen" class="iconfont icon-weibiaoti10 player-btn" title="全屏" @click="fullscreenSwich"></i>
          <i v-if="fullscreen" class="iconfont icon-weibiaoti11 player-btn" title="退出全屏" @click="fullscreenSwich"></i>
        </div>
      </div>
    </div>

</template>
<script>
import Device from '@/api/Device';
import {apiResult} from "@/libs/util";
export default {
  props: {
    scale: {
      type: Boolean,
      default: false //视频画面完全填充canvas区域
    },
    customStyle:{
      type: Object,
      default:function(){
        return{
          //backgroundColor: 'rgb(100,100,227)'
          backgroundColor:'rgb(0,21,41)'
        }
      }
      //default:()=>{backgroundColor: 'rgb(200,100,227)'}  //主要是为了自定义背景颜色
    },
    deviceCode:{
      type: String,
      default: ()=>{return "未设置设备号"}
    }
  },
  watch:{
    currentVolume(val){
      //console.log(">>>>>> CommPlayer.watch: currentVolume/100=%o",this.currentVolume/100);
      if (!!this.player){
        this.player.setVolume(this.currentVolume/100);
      }
    },
    currentBuffer(val){
      if (!!this.player){
        this.player.setBufferTime(this.currentBuffer/0.2);
      }
    },
    playing(newValue,oldValue){
      console.log(">>>>>>>>> oldValue=%o,newValue=%o",oldValue,newValue);
      if (oldValue == true && newValue == false){
        if (!!this.player){
          this.rePlayTimer = setInterval(this.playStart, 30000);
        }
      }else if (oldValue == false && newValue == true){
        if (!!this.rePlayTimer){
          clearInterval(this.rePlayTimer);
          this.rePlayTimer=null;
        }
      }
    }

  },

  data() {
    return{
      api: new Device(),
      deviceId:null,
      channelId:null,
      performance:{
        desc:"流畅",
        time: 0,
        orginValue:0,
        currValue:1,
        set: (value)=> {
          if (this.performance.orginValue == value){
            this.performance.time++;
          }else{
            this.performance.time=0;
          }
          if (this.performance.time >= 5){
            this.performance.currValue = value; //0:"卡顿" 1:"流畅" 2:"非常流畅"
            this.performance.time=0;
          }
          this.performance.orginValue = value;
        }
      },
      //performances:0,
      currentVolume:50,
      isDebug:true,
      loaded:false,
      playing:false,
      isNotMute: false,
      player: null,
      fullscreen:false,
      videoUrl:null,
      kBps:0.0,
      vod: true, // 点播
      btnDom:null,
      supportDblclickFullscreen: true,//// 是否支持屏幕的双击事件，触发全屏，取消全屏事件。
      volume:{
        current: 50,
        min:1,
        max:100
      },
      currentBuffer:1,
      buffer:{
        current: 1,
        min:1,
        max:8
      },
      rePlayTimer:null
    }
  },
  mounted() {
    this.player = this.createPlayer();
    this.btnDom = this.$refs.buttonsBox;//document.getElementById("buttonsBox");
  },
  beforeDestroy(){
    if (this.isDebug)
      console.log("*****player destroy*******");
    if (this.player ){
      this.player.destroy();
    }
    if (!!this.rePlayTimer){
      clearInterval(this.rePlayTimer);
      this.rePlayTimer=null;
    }

  },

  methods:{
    playStart(){
      console.log(">>>>>> Commplayer.playStart deviceId=%o,channelId=%o",this.deviceId,this.channelId)
      if (!!this.deviceId && !!this.channelId){
        this.api.playStart(this.deviceId,this.channelId).then(res=> {
          apiResult(res.data,false,result=>{
            this.player.show = true;
            this.play(result.data.ws_flv);
          });
        })
      }else{
        if (!!this.rePlayTimer) {
          clearInterval(this.rePlayTimer);
          this.rePlayTimer=null;
        }
      }
    },
    fullscreenSwich(){
      let isFull = this.isFullscreen()
      this.player.setFullscreen(!isFull)
      this.fullscreen = !isFull;
    },
    isFullscreen: function (){
      return document.fullscreenElement ||
        document.msFullscreenElement  ||
        document.mozFullScreenElement ||
        document.webkitFullscreenElement || false;
    },
    stop(){
      this.videoUrl = null;
      if (this.player){
        this.player.destroy();
        this.$refs.container.appendChild(this.btnDom);
      }
      this.loaded=false;
      this.playing=false;
      this.player=null;
      if (!!this.rePlayTimer) {
        clearInterval(this.rePlayTimer);
        this.rePlayTimer=null;
      }
    },
    isPlaying(){
      return this.playing;
    },
    playBtnClick(){
      this.playStart();
      //if (this.player){
      //  this.play(this.videoUrl);
      //}
    },
    pause(){
      if (this.player) {
        this.player.pause();
      }
      this.playing=false;
    },
    play(videoUrl,deviceId,channelId){
      console.log("CommPlayer.play: deviceId=%o,channelId=%o",deviceId,channelId);
      if (!!deviceId){this.deviceId = deviceId}
      if (!!channelId){this.channelId = channelId}

      let _this = this;
      /** 这里不能用箭头函数，this会指向调用它的上一层页面 */
      if (videoUrl === this.videoUrl && this.playing == true){
          return;
      }
      this.videoUrl = videoUrl;
      if (!!this.player){
        this.player.destroy();
        this.loaded=false;
        this.$refs.container.appendChild(this.btnDom);
      }
      this.playing=false;
      this.player = this.createPlayer();
    },

    createPlayer(){
      let _this = this;
      let options =  {};
      let jplayer = new window.Jessibuca(Object.assign(
        {
          container: _this.$refs.container,
          videoBuffer: 1, // 最大缓冲时长，单位秒
          isResize: this.scale, //视频画面完全填充canvas区域
          isFlv: true,
          decoder: process.env.BASE_URL + "jessibuca/index.js",
          text: "",//"TN-28181",
          //background: "jessibuca/player.png",
          loadingText: "加载中",
          hasAudio: true,//typeof (this.hasAudio) =="undefined"? true: this.hasAudio,
          debug: false,
          supportDblclickFullscreen: _this.supportDblclickFullscreen,
          operateBtns: {
            fullscreen: false,
            screenshot: false,
            play: false,
            audio: false,
          },
          record: "record",
          vod: _this.vod,
          forceNoOffscreen: false,//this.forceNoOffscreen,
          isNotMute: this.isNotMute,
        },
        options
      ));
      jplayer.on("load", function () {
        if (_this.isDebug) {
          console.log("on load init");
          console.log(_this.videoUrl);
        }
        if (_this.videoUrl){
          jplayer.play(_this.videoUrl);
          _this.loaded=true;
        }
      });
      jplayer.on("timeout", function (error) {
        if (_this.isDebug)
          console.log("on timeout", error);
      });
      jplayer.on("loadingTimeout", function () {
        if (_this.isDebug)
          console.log("on loadingTimeout");
      });
      jplayer.on("delayTimeout", function () {
        if (_this.isDebug)
          console.log("on delayTimeout");
      });


      jplayer.on("log", function (msg) {
        if (_this.isDebug)
         console.log("on log", msg);
      });
      jplayer.on("record", function (msg) {
        if (_this.isDebug)
          console.log("on record:", msg);
      });
      jplayer.on("pause", function () {
        //console.log("on pause ");
        _this.playing = false;
      });
      jplayer.on("play", function () {
        _this.playing = true;
      });
      jplayer.on("fullscreen", function (msg) {
        //console.log("on fullscreen: %o", msg);
        _this.fullscreen = msg
      });

      jplayer.on("mute", function (msg) {
        if (_this.isDebug)
          console.log("on mute", msg);
      });
      jplayer.on("audioInfo", function (msg) {
        if (_this.isDebug)
          console.log("audioInfo", msg);
      });

      jplayer.on("videoInfo", function (msg) {
        //this.videoInfo = msg;
        if (_this.isDebug)
          console.log("videoInfo: %o", msg);

      });

      jplayer.on("bps", function (bps) {

        if (_this.isDebug)
          console.log('bps', bps);

      });
      let _ts = 0;
      jplayer.on("timeUpdate", function (ts) {
        // console.log('timeUpdate,old,new,timestamp', _ts, ts, ts - _ts);
        _ts = ts;
      });
      jplayer.on("error", function (error) {
        if (_this.isDebug)
          console.log("error: %o", error);

        if (error === jplayer.ERROR.playError) {
          console.log("播放错误，可能 url 为空,%o");
        } else if (error === jplayer.ERROR.fetchError) {
          console.log("http 请求失败");
        }else if (error === jplayer.ERROR.websocketError) {
          console.log("websocket 请求失败");
        }else if (error === jplayer.ERROR.webcodecsH265NotSupport) {
          console.log("webcodecs 解码 h265 失败");
        }else if (error === jplayer.ERROR.mediaSourceH265NotSupport) {
          console.log("mediaSource 解码 h265 失败");
        }else if (error === jplayer.ERROR.wasmDecodeError) {
          console.log("wasm 解码失败");
        }else{
          console.log("未定义错误");
        }
      });

      jplayer.on("delayTimeout", function () {
        if (_this.isDebug)
          console.log("delayTimeout");
        console.log("超时，没有数据渲染");
      });
      jplayer.on("loadingTimeout", function () {
        if (_this.isDebug)
          console.log("loadingTimeout");
        console.log("请求超时");
      });

      jplayer.on('start', function () {
        //console.log(">>>>>>>>>>>>>>> CommPllayer.onstart: this.isDebug=%o",this.isDebug);
        if (_this.isDebug)
          console.log('start');
      })

      jplayer.on("performance", function (performance) {

        let show = "";
        if (performance === 2) {
          show = "非常流畅";
        } else if (performance === 1) {
          show = "流畅";
        }else if (performance === 0) {
          show = "卡顿";
        }
        //_this.performances = performance;
        if (_this.isDebug)
          ;//console.log(show);

        _this.performance.set(performance);
      });
      jplayer.on('buffer', function (buffer) {
        //console.log('buffer', buffer);
      })

      jplayer.on('stats', function (stats) {
        if (_this.isDebug)
          ;//console.log('当前状态: %o',stats);
      })

      jplayer.on('kBps', function (kBps) {
        _this.kBps = Math.round(kBps);
      });

      // 显示时间戳 PTS
      jplayer.on('videoFrame', function () {

      })

      //
      jplayer.on('metadata', function () {

      });
      return jplayer;
    },

    /**
     * 静音或取消静音
     * @param action = 1 取消静音, 0 静音
     */
    soundOff(action){
      if (!!this.player){
        //开启声音
        if (action == 1){
          this.player.cancelMute();
          this.isNotMute = true;
        }else{
          this.player.mute();
          this.isNotMute = false;
        }

        this.play(this.videoUrl);

      }
    }
  }
}
</script>
<style>
@import "../../template.less";
.commm-player-main{
  width: 100%;
  height: 100%;
  background-color: rgb(0,21,41);
  display: flex;
  flex-direction: row;
}
#container{
  width: 100%;
  height: calc(100% - 28px);
  background-color: rgb(0,21,41);
}
.buttons-div{
  width: 100%;
  height: 28px;
  background-color: rgba(0, 0, 0, 0.98);
  position: absolute;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  left: 0;
  bottom: 0;
  user-select: none;
  z-index: 10;
}
.player-btn{
  width: 20px;
  color: rgb(255, 255, 255);
  line-height: 27px;
  margin: 0px 10px;
  padding: 0px 2px;
  cursor: pointer;
  text-align: center;
  font-size: 0.8rem !important;
}

.buttons-div-right {
  position: absolute;
  right: 0;
}

.performance-span0{
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 5px;
  width: 60px;
  height: 16px;
  font-size: 12px;
  align-items: center;
  display: flex;
  justify-content: center;
  background-color: #fa541c;
  color: #FFFFFF;
}

.performance-span1{
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 5px;
  width: 60px;
  height: 16px;
  font-size: 12px;
  align-items: center;
  display: flex;
  justify-content: center;
  background-color: #056b05;
  color: #FFFFFF;
}
.performance-span2{
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 5px;
  width: 60px;
  height: 16px;
  font-size: 12px;
  align-items: center;
  display: flex;
  justify-content: center;
  background-color: #00ff00;
}


</style>
